package net.ib.mtalk.ui.setting.display;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseActivity;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.ui.attachment.camera.CameraActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SettingChatTheme extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener{
	private ImageView mEmptyImageView;
	private TextView mBuddyBalloon;
	
	private Context mContext;
	private int mCreatedDialogID;
	
	private final int BALLOON_DIALOG = 0x00;
	private final int COLOR_DIALOG = 0x01;
	private final int LIST_DIALOG = 0x02;
	
	private final int PICK_FROM_ALBUM = 0x10;
	private final int PICK_FROM_CAMERA = 0x11;
	
	private int mSelectedBalloonColor = -1;
	private int mSelectedBgColor = -1;
	private String mSelectedBgImageUriString = null;
	private boolean bIsOpenOptionMenu = false;
	
	private Integer[] mThumbIds = {
            R.drawable.ballon_default_blue, R.drawable.ballon_mint,
            R.drawable.ballon_orange, R.drawable.ballon_yellow
    };
	
	private Integer[] mColors = new Integer[8];
	
	private ArrayList<String> mListString = new ArrayList<String>();
	
	private final static int MENU_BALLOON = 1;
	private final static int MENU_BACKGROUND = 2;
	private final static int MENU_SAVE = 3;

	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_setting_chat_theme);
		mContext = this;
		
		mColors[0] = getResources().getColor(R.color.chat_background_default);
		mColors[1] = getResources().getColor(R.color.chat_background_1);
		mColors[2] = getResources().getColor(R.color.chat_background_2);
		mColors[3] = getResources().getColor(R.color.chat_background_3);
		mColors[4] = getResources().getColor(R.color.chat_background_4);
		mColors[5] = getResources().getColor(R.color.chat_background_5);
		mColors[6] = getResources().getColor(R.color.chat_background_6);
		mColors[7] = getResources().getColor(R.color.chat_background_7);
		
		mListString.add(getString(R.string.setting_theme_change_color));
		mListString.add(getString(R.string.setting_theme_from_capture));
		mListString.add(getString(R.string.setting_theme_from_album));
		
		initControls();
		initTheme();
	}
	
	private void initTheme()
	{
		mSelectedBalloonColor = GlobalPreferences.getBalloonColor();
		mSelectedBgColor = GlobalPreferences.getBgColor();
		mSelectedBgImageUriString = GlobalPreferences.getBgImageUriString();
		
		if(mSelectedBalloonColor == -1)
			mSelectedBalloonColor = mThumbIds[0];
		
		if(mSelectedBgColor == -1 && mSelectedBgImageUriString == null)
		{
			mSelectedBgColor = mColors[0];
		}
		mBuddyBalloon.setBackgroundResource(mSelectedBalloonColor);
		if(mSelectedBgColor != -1)
			findViewById(R.id.setting_theme_bg).setBackgroundColor(mSelectedBgColor);
		else if(mSelectedBgImageUriString != null)
		{
			try {
				Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(mSelectedBgImageUriString));
				findViewById(R.id.setting_theme_bg).setBackgroundDrawable(new BitmapDrawable(bm));
			} catch (FileNotFoundException e) {
				Toast.makeText(mContext, "FileNotFound", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_MENU)
			return true;
		return super.onKeyDown(keyCode, event);

	};
	
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_BALLOON, 10, getString(R.string.setting_theme_balloon_setting)).setIcon(R.drawable.menu_icon_setting01);
		menu.add(0, MENU_BACKGROUND, 10, getString(R.string.setting_theme_bg_setting)).setIcon(R.drawable.menu_icon_setting02);
		menu.add(0, MENU_SAVE, 10, getString(R.string.save)).setIcon(R.drawable.menu_icon_setting03);
		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()){
			case MENU_BALLOON :
				showDialog(BALLOON_DIALOG);
				break;
			case MENU_BACKGROUND :
				showDialog(LIST_DIALOG);
				break;
			case MENU_SAVE :
				setPreference();
				finish();
				break;
			default:
				break;
		}
		
		return super.onMenuItemSelected(featureId, item);
	}
	
	private void initControls()
	{
		mEmptyImageView = (ImageView)findViewById(R.id.empty_iv);
		mEmptyImageView.setOnClickListener(this);
		
		mBuddyBalloon = (TextView)findViewById(R.id.setting_theme_balloon);
	}
	
	protected Dialog onCreateDialog(int id) {	
		Dialog dialog;
		mCreatedDialogID = id;
		switch(mCreatedDialogID) {
		case BALLOON_DIALOG:
			dialog = new AlertDialog.Builder(this)
					.setTitle(getString(R.string.setting_theme_dialogue_balloon))
					.setView(makeView())
					.setNegativeButton(R.string.close, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							removeDialog(BALLOON_DIALOG);
						}
					}).create();
			dialog.setOnCancelListener(new OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					removeDialog(BALLOON_DIALOG);
				}});
					return dialog;
		case COLOR_DIALOG:
			dialog = new AlertDialog.Builder(this)
					.setTitle(getString(R.string.setting_theme_change_color))
					.setView(makeView())
					.setNegativeButton(R.string.close, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							removeDialog(COLOR_DIALOG);
						}
					}).create();
			dialog.setOnCancelListener(new OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					removeDialog(COLOR_DIALOG);
				}});
					return dialog;
		case LIST_DIALOG:
			dialog = new AlertDialog.Builder(this)
					.setTitle(getString(R.string.setting_theme_bg_setting))
					.setView(makeView())
					.setNegativeButton(R.string.cancel, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							removeDialog(LIST_DIALOG);
						}
					}).create();
			dialog.setOnCancelListener(new OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					removeDialog(LIST_DIALOG);
				}});
					return dialog;
		default:
			break;
		}
		
		return super.onCreateDialog(id);
	}
	
	private View makeView()
	{
		View returnView = null;
		GridView grid = null;
		ListView listView = null;
		switch(mCreatedDialogID)
		{
		case BALLOON_DIALOG:
			grid = new GridView(this);
			grid.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			grid.setAdapter(new ImageAdapter(this));
			grid.setNumColumns(mThumbIds.length);
			grid.setOnItemClickListener(this);
			grid.setGravity(Gravity.CENTER);
			returnView = grid;
			break;
		case COLOR_DIALOG:
			grid = new GridView(this);
			grid.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			grid.setAdapter(new ImageAdapter(this));
			grid.setNumColumns(mColors.length/2);
			grid.setOnItemClickListener(this);
			grid.setGravity(Gravity.CENTER);
			grid.setVerticalSpacing(20);
			returnView = grid;
			break;
		case LIST_DIALOG:
			listView = new ListView(this);
			listView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			listView.setAdapter(new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, mListString));
			listView.setCacheColorHint(0x00000000);
			listView.setOnItemClickListener(this);
			returnView = listView;
			break;
		default:
			break;
		}
		
		return returnView;
	}
	
	public class ImageAdapter extends BaseAdapter {
		private Context mContext;
		public ImageAdapter(Context c) 
		{
		    mContext = c;
		}
		
		public int getCount() 
		{
			if(mCreatedDialogID == BALLOON_DIALOG)
				return mThumbIds.length;
			else if(mCreatedDialogID == COLOR_DIALOG)
				return mColors.length;
			
			return 0;
		}
		
		public Object getItem(int position) {
			return null;
		}
		
		public long getItemId(int position) {
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) 
			{  
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				//imageView.setPadding(8, 8, 8, 8);
			} 
			else 
			{
				imageView = (ImageView) convertView;
			}
		
			if(mCreatedDialogID == BALLOON_DIALOG)
			{
				imageView.setImageResource(mThumbIds[position]);
			}
			else if(mCreatedDialogID == COLOR_DIALOG)
			{
				imageView.setBackgroundColor(mColors[position]);
			}
			
			return imageView;
		}
	}

	public void onOptionsMenuClosed(Menu menu) {
		super.onOptionsMenuClosed(menu);
		bIsOpenOptionMenu = false;
	};
	
	public void onClick(View v) 
	{
		if(v.equals(mEmptyImageView))
		{
			Log.e("test", ""+bIsOpenOptionMenu);
			if(!bIsOpenOptionMenu)
			{
				openOptionsMenu();
				bIsOpenOptionMenu = true;
			}
		}
	}
	
	private void setPreference()
	{
		GlobalPreferences.setBalloonColor(mSelectedBalloonColor);
		GlobalPreferences.setBgColor(mSelectedBgColor);
		GlobalPreferences.setBgImageUriString(mSelectedBgImageUriString);
		
		Toast.makeText(mContext, R.string.save_complete_msg, Toast.LENGTH_SHORT).show();
	}

	public void onItemClick(AdapterView<?> arg0, View v, int pos, long id) 
	{
		switch(mCreatedDialogID)
		{
		case BALLOON_DIALOG:
			mSelectedBalloonColor = mThumbIds[pos];
			mBuddyBalloon.setBackgroundResource(mSelectedBalloonColor);
			break;
		case COLOR_DIALOG:
			mSelectedBgColor = mColors[pos];
			mSelectedBgImageUriString = null;
			findViewById(R.id.setting_theme_bg).setBackgroundColor(mSelectedBgColor);
			break;
		case LIST_DIALOG:
			if(pos == 0)
				showDialog(COLOR_DIALOG);
			else if(pos == 1)
			{
				Intent i = new Intent(mContext, CameraActivity.class);
				startActivityForResult(i, PICK_FROM_CAMERA);
			}
			else if(pos == 2)
			{
				Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(i, PICK_FROM_ALBUM);
			}
			
			removeDialog(LIST_DIALOG);
			break;
		default:
			break;
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if(requestCode == PICK_FROM_ALBUM || requestCode == PICK_FROM_CAMERA) 
		{
			if (resultCode == Activity.RESULT_OK) 
			{ 
				try {
					Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
					findViewById(R.id.setting_theme_bg).setBackgroundDrawable(new BitmapDrawable(bm));
					mSelectedBgImageUriString = data.getData().toString();
					mSelectedBgColor = -1;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private boolean isChanged()
	{
		if(mSelectedBalloonColor != GlobalPreferences.getBalloonColor() 
				|| mSelectedBgColor != GlobalPreferences.getBgColor() 
				|| mSelectedBgImageUriString != GlobalPreferences.getBgImageUriString())
			return true;
		
		return false;
	}
	
	public void onBackPressed() {
		if(isChanged())
		{
			new AlertDialog.Builder(mContext).setMessage(getString(R.string.save_confirm_msg))
			.setPositiveButton(R.string.yes, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					setPreference();
					finish();
				}
			})
			.setNegativeButton(R.string.no, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					finish();
				}
			}).create().show();
		}
		else
		{
			super.onBackPressed();
		}
	};
}
